/*-
 * Copyright (c) 2009-2010 David Forsythe.
 * See LICENSE file for license details.
 */

#include <stdio.h>
#include <stdlib.h>

#include "internal.h"

#define MAGIC 0x00000000

static void _pkg_repository_check_magic(struct pkg_repository *, const char *);

static void
_pkg_repository_check_magic(struct pkg_repository *rp, const char *func)
{
        if (rp->magic != MAGIC) {
                PKG_CLIENT_CRASH(func, "repository magic number mismatch");
        }
}

void
_pkg_repository_set_vtable(struct pkg_repository *rp,
        struct pkg_repository_vtable *vt)
{
        rp->vtable = vt;
}

struct pkg_repository *
pkg_repository_create(void)
{
        struct pkg_repository *rp;

        rp = calloc(1, sizeof(*rp));
        if (rp == NULL) {
                return (NULL);
        }

        rp->internal = NULL;
        rp->vtable = NULL;
        rp->magic = MAGIC;

        return (rp);
}

int
pkg_repository_open(struct pkg_repository *rp, const char *location, 
        u_int flags)
{
        int r;

        _pkg_repository_check_magic(rp, __func__);

        r = rp->vtable->open(rp, location, flags);

        return (r);
}

FILE *
pkg_repository_fetch_pkg(struct pkg_repository *rp, const char *name, 
        char **fname, size_t *size, u_int flags)
{
        FILE *f;

        _pkg_repository_check_magic(rp, __func__);

        f = rp->vtable->fetch_pkg(rp, name, fname, size, flags);
        if (f == NULL) {
                return (NULL);
        }
        return (f);
}

int
pkg_repository_close(struct pkg_repository *rp)
{
        int r;

        _pkg_repository_check_magic(rp, __func__);

        r = rp->vtable->close(rp);
        if (r != PKG_OK) {
                return (r);
        }

        rp->status = CLOSED;

        return (PKG_OK);
}

void
pkg_repository_release(struct pkg_repository *rp)
{
        _pkg_repository_check_magic(rp, __func__);

        if (rp->status == OPEN) {
                rp->vtable->close(rp);
        }
        free(rp);
}
